package sys.spvisor.console.controller;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import sys.spvisor.core.common.ModifyPeopleException;
import sys.spvisor.core.common.PermissionException;
import sys.spvisor.core.entity.people.TPeople;
import sys.spvisor.core.entity.project.PeopleProjectBigClass;
import sys.spvisor.core.entity.project.TFileForm;
import sys.spvisor.core.entity.project.TProject;
import sys.spvisor.core.entity.project.TProjectPeople;
import sys.spvisor.core.entity.project.TSendCard;
import sys.spvisor.core.service.people.PeopleService;
import sys.spvisor.core.service.project.DispatchService;
import sys.spvisor.core.service.project.ProjectService;


@Controller
@RequestMapping("/dispatch")
public class DispatchController {
	
	@Autowired
	DispatchService dispatchService;
	@Autowired
	ProjectService projectService;
	@Autowired
	PeopleService peopleService;
	
	@RequestMapping("/selectByStationStatus.ajax")	
	public @ResponseBody List<PeopleProjectBigClass> selectByStationStatus() {
		
		List<PeopleProjectBigClass> lists = dispatchService.selectPeople();
		return lists;
	}
	
	@Transactional
	@RequestMapping("/dispatchGroupLeaderAndMember.ajax")    
   	public @ResponseBody Map<String, Object> dispatchGroupLeaderAndMember(Integer projectId,String projectGroupLeader,String projectGroupLeaderId,String projectMember_total, String projectMemberId_total) {
   		Map<String, Object> result = new HashMap<String, Object>(2);
   		List<TProjectPeople> groupLeader = new ArrayList<TProjectPeople>();
   		List<TProjectPeople> members = new ArrayList<TProjectPeople>();
   		TProject project = projectService.selectByPrimaryKey(projectId);
   		Date inProTime = project.getBegintime();
   		try {
   			if(projectGroupLeaderId != null && !projectGroupLeaderId.equals("")){
   	   			TProjectPeople groupLeader1 = new TProjectPeople();
   	   			groupLeader1.setPpInProTime(inProTime);
   	   			groupLeader1.setPpMsgid(projectId);
   	   			groupLeader1.setPpPeopleid(Integer.valueOf(projectGroupLeaderId));
   	   			groupLeader1.setPpProRoleDesc("监理组长");
   	   			groupLeader1.setPpStatus("O");
   	   			groupLeader1.setPpUsername(projectGroupLeader);
   	   			groupLeader.add(groupLeader1);
   	   		}
   	   		String[] memberName = projectMember_total.split("&");
   	   		String[] memberId = projectMemberId_total.split("&");
   	   		if(memberName.length != memberId.length){
   	   			System.out.println("监理员id数目和姓名数目不一致！");
   	   			throw new Exception();
   	   		}
   	   		if(memberId != null && memberId.length > 0 && !memberId[0].equals("")){
   	   			for(int i = 0; i < memberId.length; i++){
   	   				if(memberId[i].equals("#"))
   	   					continue;
   	   				else{
   	   					TProjectPeople member = new TProjectPeople();
   	   					member.setPpInProTime(inProTime);
   	   					member.setPpMsgid(projectId);
   	   					member.setPpPeopleid(Integer.valueOf(memberId[i]));
   	   					member.setPpProRoleDesc("监理员");
   	   					member.setPpStatus("O");
   	   					member.setPpUsername(memberName[i]);
   	   					members.add(member);
   	   				}
   	   			}
   	   		}
   	   		
   			dispatchService.dispatchGroupLeaderAndMemberByProjectIdAndPost(projectId,"监理组长",groupLeader);
   			dispatchService.dispatchGroupLeaderAndMemberByProjectIdAndPost(projectId,"监理员",members);
			result.put("success", true);
			result.put("message", "派遣成功！");
		} catch (PermissionException e) {
			result.put("success", false);
			result.put("message", e.getMessage());
		}catch (ModifyPeopleException e) {
			result.put("success", false);
			result.put("message", e.getMessage());
		}catch (Exception e) {
			result.put("success", false);
			result.put("message", "派遣失败！");
		}
   		return result;
   		
   	}
	
	@RequestMapping("/getPeopleByProjectId.ajax")	
	public @ResponseBody Map<String,Object> getPeopleByProjectId(Integer projectId) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<TProjectPeople> lists1 = dispatchService.getPeopleByProjectIdAndPost(projectId,"项目总监");
		result.put("projectChief", lists1);
		List<TProjectPeople> lists2 = dispatchService.getPeopleByProjectIdAndPost(projectId,"项目经理");
		result.put("projectManager", lists2);
		List<TProjectPeople> lists3 = dispatchService.getPeopleByProjectIdAndPost(projectId,"监理组长");
		result.put("groupLeader", lists3);
		List<TProjectPeople> lists4 = dispatchService.getPeopleByProjectIdAndPost(projectId,"监理员");
		result.put("member", lists4);
		return result;
	}
	
	@RequestMapping("/getGroupLeaderAndMemberByProjectId.ajax")
	public @ResponseBody Map<String,Object> getGroupLeaderAndMemberByProjectId(Integer projectId) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<TProjectPeople> lists1 = dispatchService.getPeopleInProByProjectIdAndPost(projectId,"监理组长");
		TProjectPeople groupLeader = null;
		if(lists1 != null && lists1.size() > 0){
			groupLeader = lists1.get(0);
		}
		result.put("groupLeader", groupLeader);
		List<TProjectPeople> lists2 = dispatchService.getPeopleInProByProjectIdAndPost(projectId,"监理员");
		result.put("member", lists2);
		return result;
	}
	
	@RequestMapping("/saveProjectPeople.ajax")	
	public @ResponseBody Map<String,Object> saveProjectPeopleByProjectIdAndPost(Integer projectId,String post,String[] projectPeopleId,String[] peopleId,String[] peopleName,String[] inProjectDate,String[] outProjectDate) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<TProjectPeople> tProjectPeoples = new ArrayList<TProjectPeople>();
		if(post.equals("projectChief"))
			post = "项目总监";
		else if(post.equals("projectManager"))
			post = "项目经理";
		else if(post.equals("groupLeader"))
			post = "监理组长";
		else if(post.equals("member"))
			post = "监理员";
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); 
		TProjectPeople tProjectPeople;
		try {
			for(int i = 1;i < peopleId.length; i++){
				if(peopleId[i].length() <= 0 || inProjectDate[i].length() <= 0){
					throw new ModifyPeopleException("姓名和进入项目日期是必填项！");
				}
				tProjectPeople = new TProjectPeople();
				if(projectPeopleId != null && i < projectPeopleId.length)
					tProjectPeople.setProjectPeopleId(Integer.valueOf(projectPeopleId[i]));
				tProjectPeople.setPpMsgid(projectId);
				tProjectPeople.setPpProRoleDesc(post);
				tProjectPeople.setPpStatus(post);
				tProjectPeople.setPpPeopleid(Integer.valueOf(peopleId[i]));
				tProjectPeople.setPpUsername(peopleName[i]);
				tProjectPeople.setPpInProTime(new Date(sf.parse(inProjectDate[i]).getTime()));
				if(outProjectDate[i].equals("")){
					tProjectPeople.setPpOutProTime(null);
					tProjectPeople.setPpStatus("O");
				}
				else{
					if(sf.parse(outProjectDate[i]).after(new java.util.Date()))
						throw new ModifyPeopleException("离开项目日期不能晚于当天！");
					else{
						tProjectPeople.setPpOutProTime(new Date(sf.parse(outProjectDate[i]).getTime()));
						tProjectPeople.setPpStatus("C");
					}
				}
				tProjectPeoples.add(tProjectPeople);
			}
			dispatchService.saveProjectPeopleByProjectIdAndPost(projectId,post,tProjectPeoples);
			result.put("success", true);
			result.put("message", "保存成功！");
		} catch (ModifyPeopleException e) {
			result.put("success", false);
			result.put("message", e.getMessage());
		} catch (Exception e) {
			result.put("success", false);
			result.put("message", "保存失败！");
		}
		return result;
	}
	
	
	@RequestMapping("/deleteByProjectPeopleId.ajax")    
   	public @ResponseBody Map<String, Object> deleteByProjectPeopleId(Integer projectPeopleId) {
   		Map<String, Object> result = new HashMap<String, Object>(2);
   		try {
   			dispatchService.deleteByProjectPeopleId(projectPeopleId);
			result.put("success", true);
			result.put("message", "删除成功！");
		} catch (Exception e) {
			result.put("success", false);
			result.put("message", "删除失败！");
		}
   		return result;
   		
   	}
	
	@RequestMapping("/getDispatchFileInfo.ajax")
	public @ResponseBody Map<String,Object> getDispatchFileInfo(Integer projectId) {
		Map<String, Object> result = new HashMap<String, Object>();
        List<TFileForm> tFileForm = dispatchService.selectDispatchFileByProjectId(projectId);
		result.put("tFileForm", tFileForm);
		result.put("length", tFileForm.size());
		return result;
	}
	
	@Transactional
	@RequestMapping("/getSendCardInfo.ajax")
	public @ResponseBody Map<String,Object> getSendCardInfo(Integer projectId) {
		Map<String, Object> result = new HashMap<String, Object>();
		TProject project = projectService.selectByPrimaryKey(projectId);
		result.put("project", project);
		List<TProjectPeople> tpp1 = dispatchService.getPeopleInProByProjectIdAndPost(projectId, "项目总监");
		List<TProjectPeople> tpp2 = dispatchService.getPeopleInProByProjectIdAndPost(projectId, "监理组长");
		List<TProjectPeople> tpp3 = dispatchService.getPeopleInProByProjectIdAndPost(projectId, "监理员");
		List<TSendCard> sendCards = dispatchService.getSendCardByProjectId(projectId);
		TPeople chief = null;
		TPeople groupLeader = null;
		TSendCard sendCard = null;
		String members = "";
		if(tpp1.size() > 0){
			chief = peopleService.getPeopleById(tpp1.get(0).getPpPeopleid());
		}
		if(tpp2.size() > 0){
			groupLeader = peopleService.getPeopleById(tpp2.get(0).getPpPeopleid());
		}
		for(TProjectPeople member : tpp3){
			members += member.getPpUsername()+"，";
		}
		if(members.endsWith("，"))
			members = members.substring(0, members.length()-1);
		if(sendCards.size() > 0)
			sendCard = sendCards.get(0);
		result.put("chief", chief);
		result.put("groupLeader", groupLeader);
		result.put("members", members);
		result.put("sendCard", sendCard);
		return result;
	}
	
	
	@RequestMapping("/submitFileAndSendcard.ajax")    
   	public @ResponseBody Map<String, Object> submitFileAndSendcard(Integer projectId,String fileNameTotal,TSendCard sendCard,MultipartHttpServletRequest request, HttpSession session) {
		String username = (String) session.getAttribute("USER_NAME");
		Long userId =  (Long) session.getAttribute("USER_ID");
		Map<String, MultipartFile> fileMap 	= request.getFileMap();
		Map<String, Object> result = new HashMap<String, Object>(2);
   		try {
   			dispatchService.submitFileAndSendcard(projectId, fileNameTotal, sendCard, fileMap, username, userId);
			result.put("success", true);
			result.put("message", "提交成功！");
		} catch (IOException e) {
			result.put("success", false);
			result.put("message", "文件上传失败!");
		} catch(PermissionException e){
			result.put("success", false);
			result.put("message", e.getMessage());
		}catch (Exception e) {
			result.put("success", false);
			result.put("message", "提交失败！");
		}
   		return result;
   		
   	}
	

}
